]> git.saurik.com Git - apple/libdispatch.git/blob - examples/Dispatch Samples/proc.c
libdispatch-84.5.tar.gz
[apple/libdispatch.git] / examples / Dispatch Samples / proc.c
1 /*
2 * Copyright (c) 2008 Apple Inc. All rights reserved.
3 *
4 * @APPLE_DTS_LICENSE_HEADER_START@
5 *
6 * IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
7 * ("Apple") in consideration of your agreement to the following terms, and your
8 * use, installation, modification or redistribution of this Apple software
9 * constitutes acceptance of these terms. If you do not agree with these terms,
10 * please do not use, install, modify or redistribute this Apple software.
11 *
12 * In consideration of your agreement to abide by the following terms, and
13 * subject to these terms, Apple grants you a personal, non-exclusive license,
14 * under Apple's copyrights in this original Apple software (the "Apple Software"),
15 * to use, reproduce, modify and redistribute the Apple Software, with or without
16 * modifications, in source and/or binary forms; provided that if you redistribute
17 * the Apple Software in its entirety and without modifications, you must retain
18 * this notice and the following text and disclaimers in all such redistributions
19 * of the Apple Software. Neither the name, trademarks, service marks or logos of
20 * Apple Computer, Inc. may be used to endorse or promote products derived from
21 * the Apple Software without specific prior written permission from Apple. Except
22 * as expressly stated in this notice, no other rights or licenses, express or
23 * implied, are granted by Apple herein, including but not limited to any patent
24 * rights that may be infringed by your derivative works or by other works in
25 * which the Apple Software may be incorporated.
26 *
27 * The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
28 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
29 * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
31 * COMBINATION WITH YOUR PRODUCTS.
32 *
33 * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
34 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
35 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36 * ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
37 * DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
38 * CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
39 * APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * @APPLE_DTS_LICENSE_HEADER_END@
42 */
43
44 #include <stdio.h>
45 #include <string.h>
46 #include <strings.h>
47 #include <stdarg.h>
48 #include <assert.h>
49 #include <stdlib.h>
50 #include <malloc/malloc.h>
51 #include <sys/stat.h>
52 #include <sys/mman.h>
53 #include <fcntl.h>
54 #include <unistd.h>
55 #include <spawn.h>
56 #include <errno.h>
57
58 #include <libkern/OSAtomic.h>
59
60 #include <dispatch/dispatch.h>
61
62 extern char **environ;
63 dispatch_queue_t qpf;
64 volatile int exitcount = 0;
65
66 // maximum value for exitcount before we quit
67 #define proccount 2
68
69
70 struct qp_msg {
71 FILE *f;
72 char *str;
73 };
74
75 void qpf_puts(void *m_) {
76 struct qp_msg *m = m_;
77 fputs(m->str, m->f);
78 free(m->str);
79 free(m);
80 }
81
82 void qfprintf(FILE *f, const char *fmt, ...) {
83 va_list ap;
84 va_start(ap, fmt);
85 struct qp_msg *m = malloc(sizeof(struct qp_msg));
86 assert(m);
87 vasprintf(&m->str, fmt, ap);
88 m->f = f;
89 dispatch_async(qpf, ^(void) { qpf_puts(m); });
90 va_end(ap);
91 }
92
93 #define qprintf(fmt...) qfprintf(stdout, ## fmt)
94
95 /* context structure, contains a process id and the
96 * command line arguments used to launch it. Used to
97 * provide context info to the block associated
98 * with a process event source.
99 */
100 struct pinfo {
101 pid_t pid;
102 dispatch_source_t source;
103 char **argv;
104 };
105
106 /* pid_finalize() is called when the dispatch source is released.
107 * this block is attached to the attribute that is passed to dispatch_source_proc_create(),
108 * and is thus associated with the dispatch source. */
109 void pid_finalize(struct pinfo *pi) {
110 qprintf("process %d is done watching %s (%d)\n", getpid(), pi->argv[0], pi->pid);
111 dispatch_release(pi->source);
112 if (OSAtomicIncrement32(&exitcount) == proccount) {
113 qprintf("both processes exited\n");
114 dispatch_sync(qpf,^{});
115 exit(0);
116 }
117 }
118
119
120 /* pid_event() is called from a block that is associated with a process event
121 * source for a specific process id (via dispatch_source_proc_create()). When
122 * such an event occurs, pid_event() calls dispatch_source_get_context() to
123 * gain access to the pid and process name that were stored in the context at
124 * the time the block was attached to the event source.
125 */
126 #define FLAG(X) ((dispatch_source_get_data(src) & DISPATCH_PROC_##X) ? #X" " : "")
127
128 void pid_event(struct pinfo *pi) {
129 dispatch_source_t src = pi->source;
130
131 qprintf("process %d %s, flags: %x %s%s%s%s\n", pi->pid, pi->argv[0], dispatch_source_get_data(src), FLAG(EXIT), FLAG(FORK), FLAG(EXEC), FLAG(SIGNAL));
132 if (dispatch_source_get_data(src) & DISPATCH_PROC_EXIT) {
133 int s;
134 waitpid(dispatch_source_get_handle(src), &s, WNOHANG);
135 qprintf(" %s exit status %d\n", pi->argv[0], s);
136 dispatch_source_cancel(src);
137 }
138 }
139
140 /* proc_start() takes a context pointer (ppi), and a dispatch queue (pq),
141 * and spawns the process named in ppi->argv[0]. The resulting process id
142 * is stored in the context (ppi->pid). On successfully spawning the process,
143 * it creates a dispatch source for the purpose of executing the routine pid_event(pi,ev)
144 * when certain events (exit, fork, exec, reap, or signal) occur to the process.
145 */
146 void proc_start(void *ppi, dispatch_queue_t pq) {
147 struct pinfo *pi = ppi;
148
149 int rc = posix_spawnp(&pi->pid, pi->argv[0], NULL, NULL, pi->argv, environ);
150 if (rc) {
151 int e = errno;
152 qprintf("Can't spawn %s (rc=%d, e=%d %s)\n", pi->argv[0], rc, e, strerror(e));
153 } else {
154
155 dispatch_source_t dsp = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, pi->pid, DISPATCH_PROC_EXIT|DISPATCH_PROC_FORK|DISPATCH_PROC_EXEC|DISPATCH_PROC_SIGNAL, pq);
156 dispatch_source_set_event_handler_f(dsp, (dispatch_function_t)pid_event);
157 dispatch_source_set_cancel_handler_f(dsp, (dispatch_function_t)pid_finalize);
158 pi->source = dsp;
159 dispatch_set_context(dsp, pi);
160 dispatch_resume(dsp);
161
162 qprintf("process %d spawned %s: %d, watching with event source: %p\n", getpid(), pi->argv[0], pi->pid, dsp);
163
164 }
165 }
166
167 int main(int argc, char *argv[]) {
168 struct pinfo pi, pi2, pi3;
169 struct pinfo *ppi2 = & pi2, *ppi3 = &pi3;
170
171 char *av[] = {argv[0], NULL}; // set up context info (struct pinfo) for this process.
172 pi.pid = getpid();
173 pi.argv = av;
174
175 char *av2[] = {"sleep", "3", NULL}; // set up context info (struct pinfo) for the sleep tool
176 pi2.argv = av2;
177
178 char *av3[] = {"script", "/tmp/LOG", "banner", "-w80", "!", NULL}; // set up context info (struct pinfo) for the script tool
179 pi3.argv = av3;
180
181 dispatch_queue_t pq = dispatch_queue_create("PQ", NULL); // create our main processing queue
182
183 qpf = dispatch_queue_create("qprintf", NULL); // create a separate queue for printf
184
185 /* create a dispatch source that will call the routine pid_event(pi,ev)
186 * when certain events occur to the specified process (pi->pid). The dispatch source is
187 * associated with the dispatch queue that was created in this routine (pq). This example
188 * requests the block be executed whenever one of the following events occurs:
189 * exit, fork, exec, reap, or signal.
190 */
191 dispatch_source_t procSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, pi.pid, DISPATCH_PROC_EXIT|DISPATCH_PROC_FORK|DISPATCH_PROC_EXEC|DISPATCH_PROC_SIGNAL, pq);
192
193 dispatch_source_set_event_handler_f(procSource, (dispatch_function_t)pid_event);
194 dispatch_source_set_cancel_handler_f(procSource, (dispatch_function_t)pid_finalize);
195 pi.source = procSource;
196 dispatch_set_context(procSource, &pi);
197 dispatch_resume(procSource);
198
199 /* create a block (which simply calls proc_start()), and dispatch it to the queue.
200 * proc_start() will spawn the process named by ppiX->argv[0], and set up
201 * another block (containing a call to pid_event()) on an event source that
202 * will recieve process events...
203 */
204 dispatch_async(pq, ^(void) { proc_start( ppi2, pq ); }); // launch the sleep tool, and create the process watcher for it
205 dispatch_async(pq, ^(void) { proc_start( ppi3, pq ); }); // launch the script tool, and create the process watcher for it
206
207
208 dispatch_main(); // wait for all the queued and spawned items to finish...
209 }